package com.eloo.otsclient.core;

import java.net.URL;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eloo.otsclient.ui.OTSClientUI;
import com.eloo.otsclient.util.OTSOrderRequest;
import com.eloo.otsclient.util.OTSStationInfo;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlHiddenInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class OTSQueryTicketThread extends Thread {
	
	protected static Log logger= LogFactory.getLog(Thread.currentThread().getClass());
	volatile WebClient webClient;
	volatile OTSSignal isRuning; 
	
//	volatile	;
	
	public OTSQueryTicketThread(String threadname,WebClient _webClient) {
		super(threadname);
		this.webClient=_webClient; 
	}
	public OTSQueryTicketThread(ThreadGroup group,String threadname,WebClient _webClient) {
		super(group,threadname);
		this.webClient=_webClient;
		// TODO Auto-generated constructor stub
	}
	
	public OTSQueryTicketThread(ThreadGroup group,String threadname,WebClient _webClient,OTSSignal oo) {
		super(group,threadname);
		this.webClient=_webClient;
		this.isRuning=oo;
		// TODO Auto-generated constructor stub
	}
	public void run() {
		 
		OTSOrderRequest otsTicketQuery	= new OTSOrderRequest();
		String stStr = OTSClientUI.getJtextStartStation().getText().trim();
		String etStr = OTSClientUI.getJtextEndStation().getText().trim();
		String stcode = OTSStationInfo.getStatinInfo(stStr);
		String etcode = OTSStationInfo.getStatinInfo(etStr);

		otsTicketQuery.setFrom(stStr);
		otsTicketQuery.setFrom_station_telecode(stcode);
		otsTicketQuery.setTo(etStr);
		otsTicketQuery.setTo_station_telecode(etcode);
		otsTicketQuery.setStart_time_str(OTSClientUI.getJtextStartDate().getText());
		logger.info("setStart_time_str:"+ OTSClientUI.getJtextStartDate().getText()+ " stcode " + stcode + " etcode " + etcode);

		try {
			loopQuery(otsTicketQuery, 10);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	@SuppressWarnings("static-access")
	private void loopQuery(OTSOrderRequest otsTicketQuery, int times) throws Exception {  
		//final String startdate=otsTicketQuery.getStart_time_str();
		OTSClientUI.getJtextareaInfo().append("\n"+otsTicketQuery.getStart_time_str()+"开始  运行..");
		HtmlPage queryPage = getNewQueryPage();
			for (int time = 1; time < times; time++) { 
				logger.info(queryPage.asText());
				String startdate=otsTicketQuery.getStart_time_str();
				OTSClientUI.getJtextareaInfo().append("\n"+startdate+"开始   第" + time + " " + "次 运行");
				HtmlButton submitQuery = invokeFrom(otsTicketQuery,queryPage,time);  
				HtmlPage searchtrainby = submitQuery.click();
				webClient.waitForBackgroundJavaScript(35000); 
			 	webClient.waitForBackgroundJavaScriptStartingBefore(35000); 
				Thread.currentThread().sleep(5000);  
				OTSClientUI.getJtextareaInfo().append("\n第"+time+"次 "+startdate+" 点击查询结束！"); 
				logger.info("\n第"+time+" "+startdate+"点击查询结束！"+ searchtrainby.asText());
				HtmlTable tickettable = null;
				try {
					tickettable = (HtmlTable) searchtrainby.getByXPath("//table[@class='obj row20px']").get(0);
				} catch (Exception e) {
					logger.info("\n第" + time +" "+startdate+" 车票信息列表为空  (~v~)(~v~)(~v~)(~v~)(~v~)"+ searchtrainby.asText());
					OTSClientUI.getJtextareaInfo().append("\n第" + time +" "+ startdate+ "次 车票信息列表为空(~v~)(~v~)(~v~)(~v~)(~v~)");
				}
				if (tickettable != null) { 
					final	List<HtmlTableRow> list = tickettable.getRows();
					OTSClientUI.getJtextareaInfo().append("\n第" + time +"次 "+startdate+ " 开始查询是否有票 <-_-><-_->"+list.size()+"<-_-><-_-><-_-><-_->。"	);
					logger.info("\n第" + " "+startdate+ " 开始查询是否有票 <-_-><-_->"+list.size()+"<-_-><-_-><-_-><-_->。"+ searchtrainby.asText());
					showConfirmDialog(list, startdate); 
			
					} else {
						OTSClientUI.getJtextareaInfo().append("\n第" + time +"次 "+ startdate+"  开始请求新页面 。。。。。。。");
						queryPage = getNewQueryPage();  
					//	continue;
					}
				
				logger.info("\n第" + time +" "+ startdate+"请求结束..休息中" + queryPage.asText()); 
				OTSClientUI.getJtextareaInfo().append("\n第"+	startdate+"次 请求结束..休息中"  );
				Thread.currentThread().sleep(10000); 
				}
			 

	 

	}
	
	
	public   HtmlButton invokeFrom(OTSOrderRequest otsTicketQuery,HtmlPage queryPage,int time) throws Exception {
		
		HtmlForm searchtrain = queryPage.getFormByName("querySingleForm");   
		logger.info("\n 第"+time+" "+otsTicketQuery.getStart_time_str()+"开始   第" + time + " " + "次 运行"+ searchtrain.asText());
		HtmlHiddenInput fromStation = searchtrain
				.getElementById("fromStation");
		fromStation.setValueAttribute(otsTicketQuery.getFrom_station_telecode());
		HtmlTextInput fromStationText = searchtrain
				.getElementById("fromStationText");
		fromStationText.setValueAttribute(otsTicketQuery.getFrom());
		HtmlTextInput toStation = searchtrain
				.getElementById("toStationText");
		toStation.setValueAttribute(otsTicketQuery.getTo());
		HtmlHiddenInput toStationText = searchtrain
				.getElementById("toStation");
		toStationText.setValueAttribute(otsTicketQuery
				.getTo_station_telecode());
		HtmlTextInput startdatepicker = searchtrain
				.getElementById("startdatepicker");
		startdatepicker.setValueAttribute(otsTicketQuery
				.getStart_time_str());
		//webClient.waitForBackgroundJavaScriptStartingBefore(15000);
		//webClient.waitForBackgroundJavaScript(15000); 	
		HtmlButton submitQuery = searchtrain.getElementById("submitQuery");
		String stlyclass = submitQuery.getAttribute("class");
		if (stlyclass != null && stlyclass.equals("search_x")) {
			OTSClientUI.getJtextareaInfo().append("\n" + time +" "+otsTicketQuery.getStart_time_str()+" 按键是灰色  。。。。。");
		 	logger.info("\n" + time +" "+otsTicketQuery.getStart_time_str()+"按键是灰色  。。。。。");
			submitQuery.removeAttribute("class");
			submitQuery.setAttribute("class", "search_u");
		}
		OTSClientUI.getJtextareaInfo().append("\n第"+time+"次 "+otsTicketQuery.getStart_time_str()+" invoke 结束!");
		logger.info("\n第"+time+" "+otsTicketQuery.getStart_time_str()+" invoke 结束! submitQuery" +searchtrain.asXml());
	 
		return submitQuery;
	}
	
	
	

	public void showConfirmDialog(List<HtmlTableRow> list,
			String date) throws Exception {
		
		//OTSClientUI.getJtextareaInfo().append("\n火车  "+date+" 查票 开始!");
		for (HtmlTableRow htr : list) {
			synchronized (this) { 
			if (!isRuning.IsRunning()) { 
				wait();
			}
			}
			boolean tip = false;
			StringBuffer msg = new StringBuffer();
		//	OTSClientUI.getJtextareaInfo().append("\n火车  "+date+" 查票  内容："+htr.asText());
		
			if (htr == null || htr.asText().trim().equals("")) {
				continue;
			}
			msg.append(date + "  "
					+ htr.getCell(0).asText().replaceAll("[\n\t\r\\s]", "")
					+ "--\n"
					+ htr.getCell(1).asText().replaceAll("[\n\t\r\\s]", "")
					+ "--"
					+ htr.getCell(2).asText().replaceAll("[\n\t\r\\s]", "")
					+ "---"
					+ htr.getCell(3).asText().replaceAll("[\n\t\r\\s]", ""));
			String wp = htr.getCell(10).asText().replaceAll("[\n\t\r\\s]", "");
			if (wp != null && !wp.equals("") && !wp.equals("无")
					&& !wp.equals("--")) {
				logger.info("卧铺:" + wp);
				msg.append("\n卧铺" + wp);
				tip = true;
			} else {
				String yz = htr.getCell(12).asText()
						.replaceAll("[\n\t\r\\s]", "");
				if (yz != null && !yz.equals("") && !yz.equals("无")
						&& !yz.equals("--")) {
					logger.info("硬座:" + yz);
					msg.append("\n硬座" + yz);
					tip = true;
				}
			}

			//OTSClientUI.getJtextareaInfo().append("\n火车"+htr.getCell(0).asText()+" "+date+" 查票!");
			//logger.info("\n火车"+htr.getCell(0).asText()+" "+date+" 查票!");
			//synchronized (webClient) { 
			if (tip) {
				OTSClientUI.getJtextareaInfo().append("\n" + msg.toString());
				HtmlTableCell yd = htr.getCell(15);
				int choice = JOptionPane.showConfirmDialog(
						OTSClientUI.getJframeMain(), msg.toString(), date
								+ " 有票", JOptionPane.YES_NO_OPTION);
				if (choice == JOptionPane.YES_OPTION) {
				 
					final HtmlAnchor yda = (HtmlAnchor) yd.getElementsByTagName("a").get(0);
					if (yda != null && !yda.getAttribute("onclick").equals("")) {
						OTSOrderTicket.setOTOTSSignal(isRuning);
						if (OTSOrderTicket.propareOrder(webClient, yda, msg)) {
						//	System.out.println(order.asText());
							Thread.sleep(6000); 
							continue;
						} else {
							break;
						}  
						}
					}
				}
		//	}
		}
	//	OTSClientUI.getJtextareaInfo().append("\n火车 "+date+" 查票 结束!");
	}
	
	private  HtmlPage getNewQueryPage() {

		HtmlPage queryPage = null;
		try {
		 
		 //	WebWindow webWindow = webClient.openWindow(new URL(OTSConstants.QUERY_TRAIN_URL), "main");
		 
		 	//   WebWindow webWindow = webClient.openWindow(new URL(OTSConstants.QUERY_TRAIN_URL), "main", webClient.getCurrentWindow());  
			//  WebResponse wr= webClient.loadWebResponse(new WebRequest(new URL(OTSConstants.QUERY_TRAIN_URL)));
			//  queryPage = (HtmlPage)  webClient.getPageCreator().createPage(wr, webClient.getCurrentWindow());
		  
			//  queryPage = (HtmlPage)  webClient.getPage(webClient.getCurrentWindow(),"main"));

		 		webClient.getPage(webClient.getCurrentWindow(),new WebRequest(new URL(OTSConstants.GET_TOKEN_URL)));
			//	queryPage = webClient.getPage(new URL(OTSConstants.GET_TOKEN_URL));
			 	queryPage = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();  
			 //queryPage = 	webClient.getPage(new WebRequest(new URL(OTSConstants.QUERY_TRAIN_URL)));
				logger.info("getNewQueryPage" + queryPage.asXml());
			//	HtmlPage	queryPagex = (HtmlPage) queryPage.getAnchorByText("车票预订").click();
			//	logger.info("getNewQueryPage" + queryPagex.asXml());
		 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("getNewQueryPage" + queryPage.asText());
		return queryPage;

	}

	
}
